package com.next

class FlexField implements Comparable
{
    String name
    String description
    String dataType
    String defaultValue
    String valueConstraints
    Boolean active = true
    Integer displayOrder = 0

    SortedSet values

    User createBy
    User modifyBy

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    static belongsTo = [category: FlexFieldCategory]

    static hasMany = [values: FlexFieldValue]

    static constraints = {
        name maxSize: 64, unique: ['category']
        dataType inList: ['String', 'Integer', 'Double', 'Date', 'Datetime', 'List', 'Customization']
        defaultValue maxSize: 64, nullable: true, blank: true
        valueConstraints maxSize: 1024, nullable: true, blank: true

        createBy nullable: true, blank: true
        modifyBy nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
    }

    static mapping = {
        sort 'category', 'name'
    }

    @Override
    int compareTo(Object FlexField)
    {

        def flexField = (FlexField) FlexField
        if (displayOrder == flexField.displayOrder)
        {
            return 0
        }
        else if (displayOrder > flexField.displayOrder)
        {
            return 1
        }
        else
        {
            return -1
        }
    }

    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)

        switch (dataType)
        {
        case "String":
            break
        case "Integer":
            valueConstraints = "^-?(([1-9]\\d*)|0)"
            break
        case "Double":
            valueConstraints = "^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)"
            break
        case "Date":
            // 2014-01-01 or 2014/01/01
            valueConstraints = "^(\\d{1,4})(-|\\/|\\\\)(\\d{1,2})\\2(\\d{1,2})"
            break
        case "Datetime":
            // 2014-01-01 12:00:00
            valueConstraints = "^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\s+(20|21|22|23|[0-1]\\d):[0-5]\\d:[0-5]\\d"
            break
        case "List":
            break
        case "Customization":
            break
        }
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)

        switch (dataType)
        {
        case "String":
            break
        case "Integer":
            break
        case "Double":
            break
        case "Date":
            break
        case "Datetime":
            break
        }
    }
}
